
#include <head.h>


int main() {
    int nfds;
    struct epoll_event ev, events[5];
    struct sockaddr_in clientaddr, serveraddr;
    int epfd, listenfd, maxi, i, sock_fd, conn_fd, n;
    char buff[100] = {0};
    socklen_t clilen;

    epfd = epoll_create(100);
    listenfd = socket(AF_INET, SOCK_STREAM, 0);
    ev.data.fd = listenfd;
    ev.events = EPOLLIN;

    epoll_ctl(epfd, EPOLL_CTL_ADD, listenfd, &ev);
    memset(&serveraddr, 0, sizeof(serveraddr));
    serveraddr.sin_family = AF_INET;
    serveraddr.sin_addr.s_addr = htons(INADDR_ANY);
    serveraddr.sin_port = htons(8888);
    bind(listenfd, (struct sockaddr *) &serveraddr, sizeof(serveraddr));
    listen(listenfd, 5);

    while (1) {
        nfds = epoll_wait(epfd, events, 5, 500);
        for (int i = 0; i < nfds; i++) {
            if (events[i].data.fd == listenfd) {
                clilen = sizeof(struct sockaddr_in);
                conn_fd = accept(listenfd,
                                 (struct sockaddr *) &clientaddr, &clilen);
                printf("accept a new client %s\n", inet_ntoa(clientaddr.sin_addr));
                ev.data.fd = conn_fd;
                ev.events = EPOLLIN;
                epoll_ctl(epfd, EPOLL_CTL_ADD, conn_fd, &ev);
                // 这个是在内核里面写的东西 外面看不到的 只能通过下次执行看到
            } else if (events[i].events & EPOLLIN) {
                sock_fd = events[i].data.fd;
                if (sock_fd < 0) { continue; }
                n = recv(sock_fd, buff, 100, 0);
                if (n == 0) {
                    close(sock_fd);
                    printf("关闭 %d \n", events[i].data.fd);
                    events[i].data.fd = -1;
                }
                printf("get %d ::%s", events->data.fd, buff);
                ev.data.fd = sock_fd;
                ev.events = EPOLLOUT;
                epoll_ctl(epfd, EPOLL_CTL_MOD, sock_fd, &ev);
            } else if (ev.events & EPOLLOUT) {
                sock_fd = events[i].data.fd;
                if (sock_fd < 0) { continue; }
                send(sock_fd, "i am epoll", 100, 0);

                ev.data.fd = sock_fd;
                ev.events = EPOLLIN;
                epoll_ctl(epfd, EPOLL_CTL_MOD, sock_fd, &ev);

            }

        }
    }
}
